import { ref } from 'vue'

import { defineStore } from 'pinia'

import { addRoutes, generateRoutes, resetRouter } from '@/router'

import { getProjectMenu } from '@/api/project'

import { getMenu as _getMenu, setMenu } from '@/utils/auth'

import { useUserStore } from './user'

export const useProjectStore = defineStore('project', () => {
  const menu = ref<any[]>([])

  const getMenu = (data: any) => {
    return new Promise((resolve, reject) => {
      getProjectMenu({ uid: data.uid, pid: data.pid })
        .then((res: any) => {
          if (res.length > 0) {
            const route = generateRoutes(res)
            menu.value = route

            // 重新生成路由
            const originRoutes = useUserStore().asyncRoutes

            const projectRoutes: any = originRoutes.filter((route) => route.path === '/project')

            projectRoutes[0].children = [projectRoutes[0].children[0], ...route]

            resetRouter()

            addRoutes(originRoutes)

            // menu重新设
            const menus = _getMenu()

            const _projectRoutes: any = menus.filter((route: any) => route.path === '/project')
            _projectRoutes[0].children = [_projectRoutes[0].children[0], ...res]

            setMenu(menus)

            resolve(route)
          }
        })
        .catch((error: Error) => {
          reject(error)
        })
    })
  }
  return {
    menu,
    getMenu,
  }
})
